package com.norma.netty.study.bio;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhangchaofeng
 * @date 2020/10/1
 * @description
 */
@Slf4j
public class BioServer {

    @SneakyThrows
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        log.info("server started ~");
        while (true) {
            //监听，等待客户连接
            final Socket accept = serverSocket.accept();
            log.info("client has been connected ~");
            //创建线程与客户端通讯
            executorService.execute(() -> handler(accept));
        }
    }

    @SneakyThrows
    private static void handler(Socket socket) {
        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } finally {
            log.info("close connection ~");
            socket.close();
        }


    }


}
